﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLayer.Model.Services;
using BusinessLayer.Model.Repositories.Abstract;
using BusinessLayer.Model.Services.Abstract;
using BusinessLayer.Model.Services.Concrete;
using DataAccess.Repositories;

namespace intecnologia.Admin
{
    public partial class News : System.Web.UI.Page
    {
        INewsRepository _newsRepository = new NewsRepository();
        ISessionService _sessionService = new SessionService();
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (_sessionService.SessionExpired())
                Response.Redirect("~/Admin/Default.aspx");

            BindDataList();
        }

        protected int NewsCount()
        {
            return _newsRepository.FetchAll().Count();
        }

        private void BindDataList()
        {
            dlNews.DataSource = _newsRepository.FetchAll().OrderByDescending(n => n.Date);
            dlNews.DataBind();
        }

        protected void btnAddNews_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/EditNews.aspx");
        }

        protected void dlNews_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "EditNews")
                EditNews(new Guid(dlNews.DataKeys[e.Item.ItemIndex].ToString()));

            else if (e.CommandName == "DeleteNews")
                DeleteNews(new Guid(dlNews.DataKeys[e.Item.ItemIndex].ToString()));
        }

        private void EditNews(Guid newsID)
        {
            Response.Redirect("~/Admin/EditNews.aspx?edit=true&id=" + newsID.ToString());
        }

        private void DeleteNews(Guid newsID)
        {
            BusinessLayer.Model.Entities.News newsToDelete = _newsRepository.FetchByID(newsID);

            _newsRepository.DeleteOnSubmit(newsToDelete);
            _newsRepository.SubmitChanges();

            BindDataList();
        }
    }
}
